<template>
    <div class="goods-add-form">
        <div class="section1">
            <div class="pro_info_title" style="text-align: center;">
                <div
                    style="margin-left: 0px; height: 40px;width: 300px; text-align: center;line-height: 40px;float: left;font-weight: bold;">
                    {{ data.Picking_outbound_code }}</div>
                <div
                    style="margin: 0 auto; height: 40px;width: 250px; text-align: center;line-height: 40px;float: right;">
                    <el-button plain @click="handleEdit" :disabled="data.Picking_outbound_audit_status === '1' || data.Picking_outbound_audit_status === '2'">编辑</el-button>
                    <el-button plain @click="handleDelete" :disabled="data.Picking_outbound_audit_status === '1' || data.Picking_outbound_audit_status === '2'">删除</el-button>
                    <el-button plain @click="handAudit" :disabled="data.Picking_outbound_audit_status === '1'">审核</el-button>
                </div>
            </div>
            <hr>

            <!-- 基本信息表格 -->
            <table style="width: 100%; border-collapse: collapse;border: none;">
                <tbody>
                    <tr>
                        <td style="padding: 10px 0px; width: 15%; color: #666;">仓库</td>
                        <td style="padding: 10px 0px 10px 10px; width: 20%;">{{ cwVaule(data.Warehouse_code) }}
                        </td>
                        <td style="padding: 10px 0px 10px 10px; width: 15%; color: #666;">库区</td>
                        <td style="padding: 10px 0px 10px 10px; width: 20%;">{{ zoneValue(data.Zone_code) }}</td>
                        <td style="padding: 10px 0px; width: 15%; color: #666;">出库状态</td>
                        <td style="padding: 10px 0px 10px 10px;">{{ getStateText(data.Picking_outbound_status) }}</td>
                    </tr>
                    <tr>
                        <td style="padding: 10px 0px; color: #666;">拣货人</td>
                        <td style="padding: 10px 0px 10px 10px;">{{ userValue(data.Picking_outbound_rep_id) }}</td>
                        <td style="padding: 10px 0px 10px 10px; width: 15%; color: #666;">拣货部门</td>
                        <td style="padding: 10px 0px 10px 10px; width: 20%;">{{ deptValue(data.Picking_outbound_dept_id) }}</td>
                        <td style="padding: 10px 0px 10px 10px; width: 15%; color: #666;">出库时间</td>
                        <td style="padding: 10px 0px 10px 10px; width: 20%;">{{ data.picking_outbound_time }}</td>
                    </tr>
                    <tr>
                        <td style="padding: 10px 0px; width: 15%; color: #666;">创建人</td>
                        <td style="padding: 10px 0px 10px 10px;">{{ data.Create_by }}</td>
                        <td style="padding: 10px 0px 10px 10px; width: 15%; color: #666;">创建时间</td>
                        <td style="padding: 10px 0px 10px 10px; min-width: 180px;">{{ datetime(data.Create_time) }}</td>
                    </tr>
                    <tr>
                        <td style="padding: 10px 0px; color: #666;">修改人</td>
                        <td style="padding: 10px 0px 10px 10px;">{{ data.Update_by ||'无'}}</td>
                        <td style="padding: 10px 0px 10px 10px; color: #666;">修改时间</td>
                        <td style="padding: 10px 0px 10px 10px;min-width: 180px;">{{ datetime(data.Update_time)||'无' }}</td>
                    </tr>
                    <tr>
                        <td style="padding: 10px 0px 10px 10px; width: 15%; color: #666;">审核状态</td>
                        <td style="padding: 10px 0px 10px 10px;">{{ getAuditText(data.Picking_outbound_audit_status) }}</td>
                        <td style="padding: 10px 0px; color: #666;">审核人</td>
                        <td style="padding: 10px 0px 10px 10px;">{{ data.Picking_outbound_audit_by || '无' }}</td>
                        <td style="padding: 10px 0px 10px 10px; color: #666;">审核时间</td>
                        <td style="padding: 10px 0px 10px 10px;min-width: 180px;">{{ datetime(data.Picking_outbound_audit_time||'无') }}</td>
                    </tr>
                </tbody>
            </table>
        </div>

        <div class="section2">
            <el-table :data="detailsDatas" border style="width: 100%" :cell-style="{ textAlign: 'center' }" :header-cell-style="{
        textAlign: 'center',
        background: '#f5f7fa',
        fontWeight: 'bold',
        position: 'sticky',
        top: 0
    }">
            <el-table-column prop="pro_code" label="产品编号" width="180" />
            <el-table-column prop="pro_name" label="产品名称" />
            <el-table-column prop="pro_brand" label="品牌" />
            <el-table-column prop="pro_model" label="规格型号" />
            <el-table-column prop="measure_id" label="单位">
                <template #default="scope">
                    <span>{{ measureValue(scope.row.measure_id) }}</span>
                </template>
            </el-table-column>
            <el-table-column prop="location_code" label="库位" />
            <el-table-column prop="picking_outbound_qty" label="待出库数量" />
            <el-table-column prop="picking_for_outbound_qty" label="已出库数量" />
            <el-table-column label="未出库数量">
                <template #default="scope">
                    <span>{{  wrksjValue(scope.row) }}</span>
                </template>
            </el-table-column>
        </el-table>
        <div style="height: 40px; line-height: 40px;">
            <div style="display: inline-block; float: left;">合计</div>
            <div style="display: inline-block; float:right">出库总数量：{{ sale_total_qty }}
        </div>
    </div>

        <div class="button-group" style="position: absolute; bottom: 10px; right: 64px; display: flex; gap: 10px;">
            <el-button @click="customer_handleClose">关闭</el-button>
        </div>
    </div>
        </div>

    <el-dialog v-model="centerDialogVisible" width="385" align-center header-align="left">
        <template #header>
            <div style="text-align: left; font-size: 16px; font-weight: bold;">
                审核
            </div>
        </template>
        <hr>
        <div style="text-align: left;padding: 10px 0px;">
            <p>审核结果</p>
            <div class="my-2 ml-4">
                <el-radio-group v-model="auditStatus">
                    <el-radio value="1">通过</el-radio>
                    <el-radio value="2">驳回</el-radio>
                </el-radio-group>
            </div>
        </div>
        <hr>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="close">取消</el-button>
                <el-button type="primary" @click="updateAudit">
                    确定
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script>
import { ref, reactive, onMounted, markRaw, inject, watch } from 'vue';
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { Delete } from '@element-plus/icons-vue'
import dayjs from 'dayjs';
import { useStore } from 'vuex';

export default {
    setup() {
        const store = useStore();
        const datas = store.state.PO_UpdeteArray
        const router = useRouter();
        const Router = useRouter();
        // const route = useRoute();
        // const datas = JSON.parse(String(route.query.rowData));


        const centerDialogVisible = ref(false);
        const auditStatus = ref('1');
        const auditOpinion = ref('');
        const measureOptios = ref([])
        const userOptions = ref([])
        const cwdata = ref([])
        const zonedata = ref([])
        const deptdata = ref([])

        // 出库状态文本转换
        const getStateText = (state) => {
            return state == '0' ? '未出库' : state == '1' ? '全部出库' :  '未知';
        }

        // 审核状态文本转换
        const getAuditText = (status) => {
            if (!status) return "未审核";
            return status == '0' ? '未审核' : status == '1' ? '审核通过' : '审核驳回';
        }

        const data = reactive({
            Picking_outbound_code: '',
            Warehouse_code: '',
            Zone_code: '',
            picking_outbound_time:'',
            Picking_outbound_rep_id: '',
            Picking_outbound_dept_id: '',
            Picking_outbound_status: '',
            Picking_outbound_audit_status: '',
            Picking_outbound_audit_by: '',
            Picking_outbound_audit_time: '',
            Create_by: '',
            Create_time: '',
            Update_by: '',
            Update_time: '',
            Picking_outbound_audit_remark: '',
        });

        const detailsDatas = ref([])
        const sale_total_qty = ref(0)

        onMounted(() => {
            // console.log("Received datas:", datas);
            getUser();
            getMeasure();
            CK();
            Zone();
            Depts();
            info();
            showDetails();
        });

        function getUser() {
            axios.get("http://localhost:5181/api/User/GetUsers", {
                headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
            }).then((result) => {
                userOptions.value = result.data;
            }).catch(console.error);
        }

        function userValue(userId) {
            if (!userId) return "无";
            const user = userOptions.value.find(u => u.user_id == userId);
            return user ? user.user_name : "无";
        }

        function deptValue(deptId) {
            if (!deptId) return "无";
            const dept = deptdata.value.find(d => d.dept_id == deptId);
            return dept ? dept.dept_name : "无";
        }

        function CK() {
            axios.get("http://localhost:5181/api/Db_warehouse/WarehouseBySelect", {
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                cwdata.value = result.data
            }).catch(console.error);
        }

        function Zone() {
            axios.get("http://localhost:5181/api/Db_warehouse_zone/warehouse_zone", {
                params: {
                    warehouse_code:datas.warehouse_code 
                },
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                zonedata.value = result.data
            }).catch(console.error);
        }
        //查询部门
        function Depts() {
            axios.get("http://localhost:5181/api/Dept/DeptOpt", {
                headers: {
                    authorization: `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                deptdata.value = result.data;
                // console.info(deptdata.value);
            }).catch(console.error);
        }

        function cwVaule(row) {
            if (!row) return "无";
            const warehouse = cwdata.value.find(w => w.warehouse_code == row);
            return warehouse ? warehouse.warehouse_name : "无";
        }

        function zoneValue(row) {
            if (!row) return "无";
            const zone = zonedata.value.find(z => z.zone_code == row);
            return zone ? zone.zone_name : "无";
        }

        function handleEdit() {
            store.commit('PO_UpdeteArray', datas)
            router.push({
                path: '/main/FG/PickingUpdate',
                // query: { rowData: JSON.stringify(datas) }
            });
        }

        function handAudit() {
            if (data.Picking_outbound_audit_status === '0' || !data.Picking_outbound_audit_status) {
                centerDialogVisible.value = true;
            } else {
                // ElMessage.warning('该领料出库单已被审核，不可再次审核！');
                centerDialogVisible.value = true;
            }
        }

        function updateAudit() {
            // 构建主表数据
            const FG_Picking_Outbound_AuditDto = {
                Picking_outbound_id: datas.picking_outbound_id,
                Picking_outbound_audit_by: localStorage.getItem('userLName'),
                Picking_outbound_audit_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
                Picking_outbound_audit_status: auditStatus.value
            };
            
            // 构建明细数据
            const fg_Picking_Outbound_DetailsAuditDtos = detailsDatas.value.map(d => ({
                Picking_outbound_id: d.picking_outbound_id,
                Picking_for_outbound_qty: d.picking_for_outbound_qty,
                Picking_outbound_qty: d.picking_outbound_qty,
                Location_code:d.location_code,
                Picking_outbound_code: d.picking_outbound_code,
                Picking_outbound_details_id: d.picking_outbound_details_id,
                pro_code: d.pro_code
            }));
            
            // 构建符合后端期望的DTO结构
            const requestData = {
                FG_Picking_Outbound_AuditDto: FG_Picking_Outbound_AuditDto, // 注意属性名大小写
                fg_Picking_Outbound_DetailsAuditDtos: fg_Picking_Outbound_DetailsAuditDtos // 注意属性名大小写
            };
            
            // console.log(requestData);

            axios.put("http://localhost:5181/api/FG_Picking_Outbound/PutFg_Picking_OutboundAudit", requestData, {
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${localStorage.getItem('token')}`
                }
            }).then((result) => {
                if (result.data > 0) {
                    ElMessage.success('领料出库单审核成功！');
                    customer_handleClose();
                }
                centerDialogVisible.value = false
            }).catch((err) => {
                console.error(err)
                ElMessage.error('审核失败');
            });
        }

        function handleDelete() {
            ElMessageBox.confirm(
                '此操作将删除该领料出库单信息，是否继续？',
                '警告',
                {
                    type: 'warning',
                    icon: markRaw(Delete),
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                }
            ).then(() => {
                return axios.put('http://localhost:5181/api/Fg_Picking/PutFgPickingDelete', {
                    Picking_outbound_id: datas.Picking_outbound_id,
                    del_flag: "1"
                }, {
                    headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
                });
            }).then((result) => {
                if (result.data > 0) {
                    ElMessage.success("删除成功");
                    customer_handleClose();
                } else {
                    ElMessage.error("删除失败");
                }
            }).catch(() => {});
        }

        const closeTab = inject('closeTab');
        function customer_handleClose() {
            Router.push({ path: '/main/FG/Picking' });
            const targetPath = "/main/FG/Picking";

            if (closeTab) closeTab();

            const tabs = inject('editableTabs');
            if (tabs && !tabs.value.some(tab => tab.path === targetPath)) {
                tabs.value.push({
                    title: "领料出库",
                    name: targetPath,
                    path: targetPath
                });
            }

            const activeTab = inject('editableTabsValue');
            if (activeTab) activeTab.value = targetPath;

            router.push(targetPath);
        }

        function datetime(isoTime) {
            if (!isoTime) return '无';
            return dayjs(isoTime).format('YYYY-MM-DD HH:mm:ss');
        }

        function showDetails() {
            // console.log("Showing details:", datas.details);
            try {
                if (datas.details && Array.isArray(datas.details)) {
                    detailsDatas.value = datas.details;
                    // console.log(detailsDatas.value)
                } else {
                    detailsDatas.value = [];
                    ElMessage.warning('未找到出库明细数据');
                }
            } catch (err) {
                console.error('加载明细失败', err);
                ElMessage.error('加载明细失败');
            }
        }

        function info() {
            data.Picking_outbound_code = datas.picking_outbound_code;
            data.Warehouse_code = datas.warehouse_code;
            data.Zone_code = datas.zone_code;
            data.picking_outbound_time = datas.picking_outbound_time;    
            data.Picking_outbound_rep_id = datas.picking_outbound_rep_id;
            data.Picking_outbound_dept_id = datas.picking_outbound_dept_id;
            data.Picking_outbound_status = datas.picking_outbound_status;
            data.Picking_outbound_audit_status = datas.picking_outbound_audit_status;
            data.Picking_outbound_audit_by = datas.picking_outbound_audit_by;
            data.Picking_outbound_audit_time = datas.picking_outbound_audit_time;
            data.Picking_outbound_audit_remark = datas.Picking_outbound_audit_remark;
            data.Create_by = datas.create_by;
            data.Create_time = datas.create_time;
            data.Update_by = datas.update_by;
            data.Update_time = datas.update_time;
            // console.log(datas);
        }

        function getMeasure() {
            axios.get("http://localhost:5181/api/Dict/Get_Dict_Datas", {
                params: { dict_type: "db_measure" },
                headers: { authorization: `Bearer ${localStorage.getItem('token')}` }
            }).then((result) => {
                measureOptios.value = result.data
            }).catch(console.error);
        }

        function measureValue(row) {
            if (!row) return "无";
            const measure = measureOptios.value.find(m => m.dict_value == row);
            return measure ? measure.dict_label : "无";
        }

        function wrksjValue(row) {
            const wrksj = Number(row.Picking_for_outbound_qty) - Number(row.Picking_outbound_qty)
            return wrksj > 0 ? wrksj : 0;
        }

        watch(detailsDatas, (newVal) => {
            sale_total_qty.value = 0;
            newVal.forEach(row => {
                sale_total_qty.value += Number(row.picking_for_outbound_qty)+Number(row.picking_outbound_qty);
            });
            // console.log("明细数据变化:", newVal);
            // console.log("合计数量:", sale_total_qty.value);
        }, { deep: true, immediate: true });

        return {
            data,
            centerDialogVisible,
            auditStatus,
            auditOpinion,
            detailsDatas,
            sale_total_qty,
            getStateText,
            getAuditText,
            userValue,
            deptValue,
            handleEdit,
            handleDelete,
            customer_handleClose,
            datetime,
            handAudit,
            updateAudit,
            cwVaule,
            zoneValue,
            measureValue,
            wrksjValue,
            close: () => {
                centerDialogVisible.value = false;
                auditStatus.value = '1';
                auditOpinion.value = '';
            }
        };
    }
}
</script>

<style scoped>
.goods-add-form{
    margin-top: -40px;
}
.section2{
    margin-top: -20px;
}
.section {
    padding: 20px;
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    
}

.button-group {
    float: right;
    display: flex;
    position: flex;
    text-align: right;
    margin-top: 20px;
    height: 7%;
    align-items: center;
    width: 80.1%;
    background-color: #ffffff;
    justify-content: flex-end;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
    padding-right: 20px;
}

.section1 {
    padding: 20px;
    height: auto;
    margin-bottom: 30px;
    border: 1px solid #ebeef5;
    border-radius: 4px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.pro_info_title {
    text-align: center;
    width: 100%;
    height: 40px;
}
</style>